package com.gooseeker.modbus;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.gooseeker.modbus.bean.SensorResultBean;

/**
 * 数据解析类
 * 当前只解析一帧数据，暂不涉及流数据帧的解析
 * 一帧数据包含4点工位信息
 * @author Administrator
 */
public class DataAnalysis
{
	private static Logger logger = Logger.getLogger(DataAnalysis.class);
	
	////数据格式010410000000BD000000000000000000000000F850
	synchronized public static List<SensorResultBean> parseDataram(byte[] data)
	{
		List<SensorResultBean> list = new ArrayList<SensorResultBean>();
		SensorResultBean bean = null;
		//取得设备地址
		byte[] addrStr = new byte[1];
		System.arraycopy(data, 0, addrStr, 0, 1);
		int addr = CRC16Utils.byteArrayToInt(addrStr);
		
		//取得命令字
		byte[] cmdStr = new byte[1];
		System.arraycopy(data, 1, cmdStr, 0, 1);
		int cmd = CRC16Utils.byteArrayToInt(cmdStr);
		
		//取出数据长度
		byte[] tempStr = new byte[1];
		System.arraycopy(data, 2, tempStr, 0, 1);
		short len = CRC16Utils.byteArrayToInt(tempStr);
		
		short volt = 0;
		
		switch (cmd)
		{
		case ConstValue.PROTOCAL_KEYWORD_READ_INPUT:
			//8路数据存储，共16B，ADC为10bit精度，故用2个B来存储		
			byte[] voltData = new byte[len];
			System.arraycopy(data, 3, voltData, 0, len);
			for (int i = 0; i < len / 4; i++)
			{
				bean = new SensorResultBean();
				
				bean.setDeviceAddr(addr);
				bean.setSensorAddr(i + 1);
				volt = handleStationVolt(voltData, i * 2);
				bean.setValue1(volt);
				volt = handleStationVolt(voltData, i * 2 + 1);
				bean.setValue2(volt);
				
				logger.info(bean.toString());
				
				list.add(bean);
			}
			//voltData = null;
			//TODO数据入库，注意：当前列表有个数据，需要进行下一步处理
			break;

		default:
			System.out.println("command is not PROTOCAL_KEYWORD_READ_INPUT");
			break;
		}
		
		
		return list;
	}

	/**
	 * 根据索引解析某个工位的电压值
	 * @param data 数据位，0010 0020 | 0012 0000 | 0012 0022 | 0012 0033
	 * @param index 索引，共4对8路数据，其中一对为一个工位的信息
	 * @return
	 */
	private static short handleStationVolt(byte[] data, int index)
	{
		byte[] temp = new byte[2];
		System.arraycopy(data, index * 2, temp, 0, 2);
		short ret = CRC16Utils.byteArrayToInt(temp);
		
		if (ret < 0)
		{
			ret = (short)(0xffff + ret);
		}
		
		temp = null;
		
		return ret;
	}

	public static void main(String[] args)
	{
		//List<SensorResultBean> list = DataAnalysis.parseData(cmd);
		/*
		byte[] cmds = {0x11, 0x04, 0x10, 0x00, 0x00, 0x00, (byte) 0xbd, 0x00, 0x00, 
				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x11, (byte) 0xf8, 0x50};
		parseDataram(cmds);
		*/
		
		byte[] cmd = {0x59, 0x04, 0x10, 0x01, (byte)0xEB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, (byte)0x9e};
		parseDataram(cmd);
	}
}
